package com.qyhl.webtv.commonlib.utils.push;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;
import com.google.gson.Gson;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.PushParametersBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;

import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by helin on 2017/2/4.
 * <p>
 * 阿里推送 MessageReceiver
 */
public class MyMessageReceiver extends MessageReceiver {

    // 消息接收部分的LOG_TAG
    public static final String REC_TAG = "MPS";


    /**
     * 通知接收回调
     *
     * @param context 上下文环境
     * @param title   通知标题
     * @param summary 通知额外参数，包括部分系统自带参数：
     * @param map
     */
    @Override
    protected void onNotification(Context context, String title, String summary, Map<String, String> map) {
        if (null != map) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                Log.e(REC_TAG, "@Get diy param : Key=" + entry.getKey() + " , Value=" + entry.getValue());
            }
        } else {
            Log.e(REC_TAG, "@收到通知 && 自定义消息为空");
        }
        Log.e(REC_TAG, "收到一条推送通知 ： " + title);

    }

    @Override
    protected void onNotificationReceivedInApp(Context context, String title, String summary, Map<String, String> extraMap, int openType, String openActivity, String openUrl) {
        Log.e(REC_TAG, "onNotificationReceivedInApp ： " + " : " + title + " : " + summary + "  " + extraMap + " : " + openType + " : " + openActivity + " : " + openUrl);
    }


    /**
     * 推送消息的回调方法
     *
     * @param context
     * @param cPushMessage
     */
    @Override
    public void onMessage(Context context, CPushMessage cPushMessage) {
        try {
            BusFactory.getBus().post(new Event.ShopTopRefresh(cPushMessage.getContent()));
            Log.e(REC_TAG, "收到一条推送消息 ： " + cPushMessage.getTitle());
        } catch (Exception e) {
            Log.e(REC_TAG, e.toString());
        }
    }


    /**
     * 通知打开回调
     *
     * @param context
     * @param s
     * @param s1
     * @param s2
     */
    @Override
    protected void onNotificationOpened(Context context, String s, String s1, String s2) {
        Log.e("NotificationReceiver", s2);
        Gson gson = new Gson();
        PushParametersBean pushData = gson.fromJson(s2, PushParametersBean.class);
        //判断app是否存活
        if (isAppAlive(context, context.getPackageName())) {
            Log.e("NotificationReceiver", "the app process is alive");
            ARouter.getInstance().build(ARouterPathConstant.HOME_ACTIVITY)
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    .withSerializable("msg", pushData)
                    .navigation(context, new NavCallback() {
                        @Override
                        public void onArrival(Postcard postcard) {
                            BusFactory.getBus().post(new Event.pushSkip(pushData));
                        }
                    });

        } else {
            Log.e("NotificationReceiver", "the app process is dead");
        }
    }

    @Override
    protected void onNotificationClickedWithNoAction(Context context, String s, String s1, String s2) {
        
    }

    @Override
    protected void onNotificationRemoved(Context context, String s) {

    }


    public boolean isAppAlive(Context context, String packageName) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos
                = activityManager.getRunningAppProcesses();
        for (int i = 0; i < processInfos.size(); i++) {
            if (processInfos.get(i).processName.equals(packageName)) {
                return true;
            }
        }

        return false;
    }


}
